<?php

require_once 'rb.php';

define('DBHOST', 'db446851405.db.1and1.com');
define('DBUSER', 'dbo446851405');
define('DBPASS', 'Elonux79');
define('DBNAME', 'db446851405');

function _convert($content) {
    if(!mb_check_encoding($content, 'UTF-8') 
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
        $content = mb_convert_encoding($content, 'UTF-8'); 
    }
	
	$content = str_replace('&#39;', '\'', $content);
	$content = str_replace('&ccedil;', 'ç', $content);
	$content = str_replace('&#45;', '-', $content);
	
    return mysql_real_escape_string($content);
}

function getArrayToDBValue($item, $key, $type = 'txt')
{
	if(!isset($item[$key]))
	{
		if ($type != 'bool')
			return 'NULL';
		else
			return "'0'";
	}
		
	$value = $item[$key];
	
	if(is_array($value))
	{
		$value = implode(';', $value);
	}
	
	switch($type)
	{
		case 'int':
			return intval($value);
		
		case 'bool':
			return $value ? "'1'" : "'0'";
			
		default:
			return "'" . _convert($value) . "'";
	}
}

/*

CREATE TABLE `items` (
  `identifier` int(11) unsigned NOT NULL default '0',
  `url` varchar(255) collate utf8_unicode_ci default NULL,
  `contactName` varchar(255) collate utf8_unicode_ci default NULL,
  `date` datetime default NULL,
  `isProfessional` set('0','1') collate utf8_unicode_ci default NULL,
  `isUrgent` set('0','1') collate utf8_unicode_ci default NULL,
  `price` int(11) unsigned default NULL,
  `category` varchar(255) collate utf8_unicode_ci default NULL,
  `title` varchar(255) collate utf8_unicode_ci default NULL,
  `description` text collate utf8_unicode_ci,
  `zipcode` int(11) unsigned default NULL,
  `city` varchar(255) collate utf8_unicode_ci default NULL,
  `formUrl` varchar(255) collate utf8_unicode_ci default NULL,
  `phone` varchar(255) collate utf8_unicode_ci default NULL,
  `contactSiren` int(11) unsigned default NULL,
  `pictures` text collate utf8_unicode_ci,
  `YearModel` int(11) default NULL,
  `Kilometers` int(11) default NULL,
  `FuelType` varchar(20) collate utf8_unicode_ci default NULL,
  `GearType` varchar(20) collate utf8_unicode_ci default NULL,
  `Cylindree` int(11) default NULL,
  `Type` varchar(20) collate utf8_unicode_ci default NULL,
  `NbRoom` int(3) default NULL,
  `Surface` int(5) default NULL,
  `GES` varchar(20) collate utf8_unicode_ci default NULL,
  `EnergyClass` varchar(20) collate utf8_unicode_ci default NULL,
  `Loyer` int(11) default NULL,
  `IncludingCharges` set('0','1') collate utf8_unicode_ci default NULL,
  `IsMeubles` set('0','1') collate utf8_unicode_ci default NULL,
  `LoyerPerWeek` varchar(20) collate utf8_unicode_ci default NULL,
  `HasPiscine` set('0','1') collate utf8_unicode_ci default NULL,
  `NbSleepingRoom` int(3) default NULL,
  `Capacity` int(3) default NULL,
  `Reference` varchar(20) collate utf8_unicode_ci default NULL,
  `Sexe` varchar(20) collate utf8_unicode_ci default NULL,
  `Size` varchar(20) collate utf8_unicode_ci default NULL,
  `Vaccine` set('0','1') collate utf8_unicode_ci default NULL,
  `Puce` set('0','1') collate utf8_unicode_ci default NULL,
  UNIQUE KEY `identifier` (`identifier`),
  FULLTEXT KEY `search` (`title`,`description`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


*/

function deflateItem($item)
{
	$result = '';
	$result .= getArrayToDBValue($item, 'identifier', 'int');
	$result .= ',' . getArrayToDBValue($item, 'url');
	$result .= ',' . getArrayToDBValue($item, 'contactName');
	$result .= ',' . getArrayToDBValue($item, 'date');
	$result .= ',' . getArrayToDBValue($item, 'isProfessional', 'bool');
	$result .= ',' . getArrayToDBValue($item, 'isUrgent', 'bool');
	$result .= ',' . getArrayToDBValue($item, 'price', 'int');
	$result .= ',' . getArrayToDBValue($item, 'category');
	$result .= ',' . getArrayToDBValue($item, 'title');
	$result .= ',' . getArrayToDBValue($item, 'description');
	$result .= ',' . getArrayToDBValue($item, 'zipcode');
	$result .= ',' . getArrayToDBValue($item, 'city');
	$result .= ',' . getArrayToDBValue($item, 'formUrl');
	$result .= ',' . getArrayToDBValue($item, 'phone');
	$result .= ',' . getArrayToDBValue($item, 'contactSiren', 'int');
	$result .= ',' . getArrayToDBValue($item, 'pictures');
	$result .= ',' . getArrayToDBValue($item, 'YearModel', 'int');
	$result .= ',' . getArrayToDBValue($item, 'Kilometers', 'int');
	$result .= ',' . getArrayToDBValue($item, 'FuelType');
	$result .= ',' . getArrayToDBValue($item, 'GearType');
	$result .= ',' . getArrayToDBValue($item, 'Cylindree', 'int');
	$result .= ',' . getArrayToDBValue($item, 'Type');
	$result .= ',' . getArrayToDBValue($item, 'NbRoom', 'int');
	$result .= ',' . getArrayToDBValue($item, 'Surface', 'int');
	$result .= ',' . getArrayToDBValue($item, 'GES');
	$result .= ',' . getArrayToDBValue($item, 'EnergyClass');
	$result .= ',' . getArrayToDBValue($item, 'Loyer', 'int');
	$result .= ',' . getArrayToDBValue($item, 'IncludingCharges', 'bool');
	$result .= ',' . getArrayToDBValue($item, 'IsMeubles', 'bool');
	$result .= ',' . getArrayToDBValue($item, 'LoyerPerWeek');
	$result .= ',' . getArrayToDBValue($item, 'HasPiscine', 'bool');
	$result .= ',' . getArrayToDBValue($item, 'NbSleepingRoom', 'int');
	$result .= ',' . getArrayToDBValue($item, 'Capacity', 'int');
	$result .= ',' . getArrayToDBValue($item, 'Reference');
	$result .= ',' . getArrayToDBValue($item, 'Sexe');
	$result .= ',' . getArrayToDBValue($item, 'Size');
	$result .= ',' . getArrayToDBValue($item, 'Vaccine', 'bool');
	$result .= ',' . getArrayToDBValue($item, 'Puce', 'bool');
	return $result;
}

function DBsave($data)
{
	if(!isset($data))
		return 0;
		
	$itemsInsert = 'INSERT IGNORE INTO items (  identifier, url, contactName , date , isProfessional , isUrgent , price , category , title ,'
				. ' description , zipcode , city , formUrl , phone , contactSiren , pictures , YearModel , Kilometers , FuelType ,'
				. ' GearType , Cylindree , Type , NbRoom , Surface , GES , EnergyClass , Loyer , IncludingCharges , IsMeubles , LoyerPerWeek ,'
				. ' HasPiscine , NbSleepingRoom , Capacity , Reference , Sexe , Size , Vaccine , Puce ) VALUES ';

	$i = 0;
	foreach($data as $item)
	{
		if($i > 0)
		{
			$itemsInsert .= ',';
		}
		$itemsInsert .= '(' . deflateItem($item) . ')';
		$i++;
	}
	
	return insertSQL($itemsInsert);
}

function existInDB($table, $id)
{	
	$result = null;

	$column = ( $table == 'items' ? 'identifier' : 'id' );
	if(!is_array($id))
	{
		$sql = "select count(*) as nb from $table where $column = $id";
		$row = execOneSQL($sql);
		$result = ( $row['nb'] > 0 );
	}
	else
	{
		$result = array();
		if(checkTableExists($table))
		{
			$sql = "select $column from $table where $column in ( " . implode(',', $id) . " ) ";
			$sqlresult = execSQL($sql);
			
			while ($row = mysql_fetch_array($sqlresult)) {
				$result[] = $row[$column];
			}
		}
	}
	
	return $result;
}

function execSQL($sql, $callback = null, $option = null)
{
	mysql_connect(DBHOST, DBUSER, DBPASS) or die(mysql_error());
	mysql_select_db(DBNAME) or die(mysql_error());
	mysql_query("SET NAMES UTF8"); 
	$cursor = mysql_query($sql) or die(mysql_error());  
	
	//std case
	if(!isset($callback)) {
		return $cursor;
	}
	
	//cb case
	$index = 0;
	while( $row = mysql_fetch_array( $cursor ) ) {
		$index++;
        if (isset($callback)) {
            if (is_callable($callback)) {
                call_user_func($callback, $row, $index, $option);
            }
        }
	}
	
	return $index;
}

function execOneSQL($sql)
{
	$result = execSQL($sql);  
	return mysql_fetch_array( $result );
}

function insertSQL($sql)
{
	mysql_connect(DBHOST, DBUSER, DBPASS) or die(mysql_error());	
	mysql_select_db(DBNAME) or die(mysql_error());
	mysql_query("SET NAMES UTF8");
	mysql_query($sql) or die(mysql_error());  
	return mysql_insert_id( );
}

function checkTableExists($table)
{
	$sql = "SELECT COUNT(*) as nb FROM information_schema.tables WHERE table_schema = '" . DBNAME . "' AND table_name = '$table'";
	$row = execOneSQL($sql);
	return ( $row['nb'] > 0 );
}

function getLastDateItem()
{
	$sql = "SELECT max(date) as date FROM items";
	$row = execOneSQL($sql);
	return $row['date'];
}

?>
